package com.minelx.httpclient.core.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import java.util.HashMap;
import java.util.Map;

import static java.util.stream.Collectors.joining;

public class FormDataEntityFactory implements IEntityFactory {
	@Override
	public HttpEntity createEntity(String dataLine) {
		Map<String, String> formDataAsMap = toMap(JSON.parseObject(dataLine));
		return new StringEntity(urlEncoded(formDataAsMap), ContentType.TEXT_PLAIN);
	}

	public static Map<String, String> toMap(JSONObject headersAsJSON) {
		Map<String, String> result = new HashMap<>();
		for (Map.Entry<String, Object> entry : headersAsJSON.entrySet()) {
			result.put(entry.getKey(), entry.getValue().toString());
		}
		return result;
	}

	public static String urlEncoded(Map<String, String> formDataAsMap) {
		return formDataAsMap.entrySet().stream()
				.map(entry -> entry.getKey() + "=" + entry.getValue())
				.collect(joining("&"));
	}
}
